﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 智慧无纸化会议客户端软件.Code
{
    public class AppSetting
    {
        public static Dictionary<string, object> Data { get; set; }

        /// <summary>
        /// ApiServiceUrl
        /// </summary>
        public static string ServiceUrl { get { return GetAppSettingsValue<string>("ServiceUrl"); } }

        public static string AppId { get { return GetAppSettingsValue<string>("AppId"); } }


        public static string MacAddress
        {
            get
            {
                string mac = GetAppSettingsValue<string>("MacAddress");

                if (string.IsNullOrEmpty(mac)) mac = GenMac();

                return mac;
            }
        }

        public static void UpdateAppSetting(Dictionary<string, string> dict)
        {
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

            foreach (var kvp in dict)
            {
                var ele = config.AppSettings.Settings[kvp.Key];
                if (ele == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement(kvp.Key, kvp.Value));
                }
                else ele.Value = kvp.Value;
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        public static string GenMac()
        {
            string mac = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12).ToUpper();

            List<string> strList = new List<string>();
            int index = 0;
            while (index < mac.Length)
            {
                strList.Add(mac.Substring(index, 2));
                index += 2;
            }

            mac = string.Join("-", strList);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("MacAddress", mac);

            UpdateAppSetting(dict);

            return mac;
        }

        static T GetAppSettingsValue<T>(string name, object defaultValue = null)
        {
            string value = ConfigurationManager.AppSettings[name];

            object obj = value;
            if (string.IsNullOrEmpty(value) && Data != null && Data.ContainsKey(name))
            {
                obj = Data[name];
            }

            if (obj == null && defaultValue != null) return Common.GetValue<T>(defaultValue);

            return Common.GetValue<T>(obj);
        }
    }
}
